package cn.dakaqi.utils.jpush;


import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * Created by chunyang on 2015/3/24.
 */
public class JPushUtil implements Runnable{
    protected static final Logger logger = LoggerFactory.getLogger(JPushUtil.class);

    // demo App defined in resources/jpush-api.conf
    private static final String appKey ="641f18ede62de63855ce90e1";
    private static final String masterSecret = "deb846546005ee1fbc4b13ca";

    public static final String TITLE = "志愿者打卡器";
    public static final String ALERT_MEG = "这是简短的内容";
    public static final String MSG_CONTENT = "这是活动的内容";
    public static final String REGISTRATION_ID = "0900e8d85ef";
    public static final String TAG = "tag_api";

    static List<String> membersList = new ArrayList<String>();

    public static JPushClient jpushClient = null;
    static
    {
        jpushClient = new JPushClient(masterSecret, appKey, 3);
        membersList.add("8a48ce6142ebdf040142ebe401150001");
        membersList.add("8a282b8f5165a11b015165dfbb870023");
    }


    String alert;
    List<String> list;
    Map<String,String> map;
    String type = "all";

    public static void main(String[] args) {
        testSendPush();
    }

    public JPushUtil()
    {
    }

    public JPushUtil(String type,String alert, List<String> list, Map<String, String> map)
    {
        this.type = type;
        this.alert = alert;
        this.list = list;
        this.map = map;
    }

    public static void testSendPush() {
        // HttpProxy proxy = new HttpProxy("localhost", 3128);
        // Can use this https proxy: https://github.com/Exa-Networks/exaproxy
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);

        // For push, all you need do is to build PushPayload object.
        //PushPayload payload = buildPushObject_all_all_alert();
        PushPayload payload = buildPushObject_android_tag_alertWithTitle2();//buildPushObject_all_alias_alert();//buildPushObject_android_tag_alertWithTitle2();
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println("Got result - " + result);

        } catch (APIConnectionException e) {
            System.out.println("Connection error. Should retry later. "+ e);

        } catch (APIRequestException e) {
            System.out.println("Error response from JPush server. Should review and fix it. "+e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    public static PushPayload buildPushObject_all_all_alert() {
        return PushPayload.alertAll(ALERT_MEG);
    }

    public static PushPayload buildPushObject_all_alias_alert(String alert, List<String> list, Map<String,String> map) {
        if(null == map || map.isEmpty()|| map.size() ==0)
        {
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.android(alert, TITLE, null))
                    .build();
        }
        else
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.android(alert, TITLE, map))
                    .build();
    }
    public static PushPayload buildPushObject_single_alias_alert(String alert, String aliasName, Map<String,String> map) {

        if(null != map && map.size()>0 && !map.isEmpty())
        {
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android_ios())
                    .setAudience(Audience.alias(aliasName))
                    .setNotification(Notification.newBuilder()
                            .setAlert(alert)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(TITLE)
                                    .addExtras(map)
                                    .build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .incrBadge(1)
                                    .addExtras(map).build())
                            .build())
                    .build();
        }
        else
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android_ios())
                    .setAudience(Audience.alias(aliasName))
                    .setNotification(Notification.newBuilder()
                            .setAlert(alert)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(TITLE)
                                    .build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .incrBadge(1).build())
                            .build())
                    .build();

    }

    public static PushPayload buildPushObject_android_tag_alertWithTitle() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.android(ALERT_MEG, TITLE, null))
                .build();
    }
    public static PushPayload buildPushObject_android_tag_alertWithTitle2() {
//        return PushPayload.newBuilder()
//                .setPlatform(Platform.android())
//                .setAudience(Audience.alias("8a48ce6146849441014685053eb6000c"))
//                .setNotification(Notification.android(ALERT_MEG, TITLE, null))
//                .build();

        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(membersList))
                .setNotification(Notification.newBuilder()
                        .setAlert(ALERT_MEG)
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle(TITLE)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1).build())
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_android_and_ios(String alert,List<String> list, Map<String,String> map) {
        if(null != map && map.size()>0 && !map.isEmpty())
        {
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android_ios())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.newBuilder()
                            .setAlert(alert)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(TITLE)
                                    .addExtras(map)
                                    .build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .incrBadge(1)
                                    .addExtras(map).build())
                            .build())
                    .build();
        }
        else
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android_ios())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.newBuilder()
                            .setAlert(alert)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(TITLE)
                                    .build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .incrBadge(1).build())
                            .build())
                    .build();
    }

    public static PushPayload buildPushObject_android(String alert,List<String> list, Map<String,String> map) {
        System.out.println("jpush-----buildPushObject_android------>"+alert);
        if(null != map && map.size()>0 && !map.isEmpty())
        {
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.android(alert, TITLE, map))
                    .build();
        }
        else
            return PushPayload.newBuilder()
                    .setPlatform(Platform.android())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.android(alert, TITLE, null))
                    .build();
    }

    public static PushPayload buildPushObject_iOS(String alert,List<String> list, Map<String,String> map) {
        System.out.println("jpush-----buildPushObject_iOS------>"+alert);
        if(null != map && map.size()>0 && !map.isEmpty())
        {
            return PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.newBuilder()
                            .setAlert(alert)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(TITLE)
                                    .addExtras(map)
                                    .build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .incrBadge(1)
                                    .addExtras(map).build())
                            .build())
                    .build();
        }
        else
            return PushPayload.newBuilder()
                    .setPlatform(Platform.ios())
                    .setAudience(Audience.alias(list))
                    .setNotification(Notification.newBuilder()
                            .setAlert(alert)
                            .addPlatformNotification(AndroidNotification.newBuilder()
                                    .setTitle(TITLE)
                                    .build())
                            .addPlatformNotification(IosNotification.newBuilder()
                                    .incrBadge(1).build())
                            .build())
                    .build();
    }

    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and("tag1", "tag_all"))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(ALERT_MEG)
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                .setMessage(Message.content(MSG_CONTENT))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }

    public static void sendListMessage(String type,String alert,List<String> list, Map<String,String> map)
    {
        Thread thread = new Thread(new JPushUtil(type,alert,list, map));
        thread.start();
    }
    public static void send2AndroidListMessage(String type,String alert,List<String> list, Map<String,String> map)
    {
        Thread thread = new Thread(new JPushUtil(type,alert,list, map));
        thread.start();
    }
    public static void send2iOSListMessage(String type,String alert,List<String> list, Map<String,String> map)
    {
        Thread thread = new Thread(new JPushUtil(type,alert,list, map));
        thread.start();
    }
    public static void sendAllListMessage(String alert,List<String> list, Map<String,String> map)
    {

        System.out.println("jpush-----sendAllListMessage------>"+alert);

        ResourceBundle bundle = ResourceBundle.getBundle("resources/parameter");
        String WebRoot = bundle.getString("app.root.path");
        if(WebRoot.indexOf("www.dakaqi.cn") == -1)
            return;

        if(null == list || list.size() ==0)
            return;
        PushPayload payload = JPushUtil.buildPushObject_android_and_ios(alert, list, map);//buildPushObject_android_tag_alertWithTitle2();
        try {
            PushResult result = JPushUtil.jpushClient.sendPush(payload);
            System.out.println("Got result - " + result);

        } catch (APIConnectionException e) {
            System.out.println("Connection error. Should retry later. "+ e);

        } catch (APIRequestException e) {
            System.out.println("Error response from JPush server. Should review and fix it. "+e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    public static void sendSingleMessage(String alert, String aliasName, Map<String,String> map)
    {
        ResourceBundle bundle = ResourceBundle.getBundle("resources/parameter");
        String WebRoot = bundle.getString("app.root.path");
        if(WebRoot.indexOf("www.dakaqi.cn") == -1)
            return;

        if(null == aliasName || aliasName.equals(""))
            return;
        System.out.println("jpush------sendSingleMessage----->"+alert);
        PushPayload payload = JPushUtil.buildPushObject_single_alias_alert(alert,aliasName, map);//buildPushObject_android_tag_alertWithTitle2();
        try {
            PushResult result = JPushUtil.jpushClient.sendPush(payload);
            System.out.println("Got result - " + result);

        } catch (APIConnectionException e) {
            System.out.println("Connection error. Should retry later. "+ e);

        } catch (APIRequestException e) {
            System.out.println("Error response from JPush server. Should review and fix it. "+e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
            System.out.println("Msg ID: " + e.getMsgId());
        }
    }

    @Override
    public void run()
    {
        try
        {
            if(type.equals("all"))
            {
               /* int totalPage = list.size()/1000+1;
                for(int i=1;i<=totalPage;i++)
                {
                    Page p = new Page();
                    p.setPage(i);
                    p.setNumberPerPage(1000);
                    List<String> temp = ResultByPage.getResultByPage(list, p);
                    sendAllListMessage(this.alert, temp, this.map);
                    Thread.sleep(1000*60);
                }*/
            }
            else if(type.equals("android"))
            {
                /*int totalPage = list.size()/1000+1;
                for(int i=1;i<=totalPage;i++)
                {
                    Page p = new Page();
                    p.setPage(i);
                    p.setNumberPerPage(1000);
                    List<String> temp = ResultByPage.getResultByPage(list, p);
                    buildPushObject_android(this.alert, temp, this.map);
                    Thread.sleep(1000*60);
                }*/

            }
            else if(type.equals("iOS"))
            {
                /*int totalPage = list.size()/1000+1;
                for(int i=1;i<=totalPage;i++)
                {
                    Page p = new Page();
                    p.setPage(i);
                    p.setNumberPerPage(1000);
                    List<String> temp = ResultByPage.getResultByPage(list, p);
                    buildPushObject_iOS(this.alert, temp,this.map);
                    Thread.sleep(1000*60);
                }*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}